import {Toast} from 'antd-mobile-rn'
import config from '$/config'


const ajaxParams = {
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, same-origin, *omit
    mode: 'cors', // no-cors, cors, *same-origin
    redirect: 'follow', // manual, *follow, error
    referrer: 'no-referrer', // *client, no-referrer
}

/*
* 超时函数
* @param fetch Promise
* @param  timeout Number
* */
const timeout = (fetch, timeout = 10000) => {
    return Promise.race([
        fetch,
        new Promise(function (resolve, reject) {
            setTimeout(() => reject({timeout: true,success: false, message: 'request timeout'}), timeout);
        })
    ]);
};

/*把POST的参数转换成GET参数*/
export const postToGet = o => {
    let arr = [];
    for(let key in o){
        arr.push(`${key}=${o[key]}`)
    }
    return arr.join('&')
}

export const post = (url, params) => {
    return timeout(fetch(config.baseUrl + url, {
        method: 'POST',
        body: params,
        ...ajaxParams
    })).catch(error => {
        if(error.timeout){
            Toast.fail('请求超时')
        }else{
            Toast.fail('请求错误')
        }
        return error
    })
}

export const get = (url, params) => {
    url = `${config.baseUrl + url}?${postToGet(params)}`;
    return timeout(fetch(url, {
         method: 'GET',
         ...ajaxParams
     })).then(res => {
        if(res.ok && res.status === 200 && res._bodyInit._data.size > 0){
             return res.json();
         }
        if(res.status === 400){
            Toast.fail('请求参数错误')
            return false
        }
        if(res.status === 500){
            Toast.fail('连接服务器失败')
            return false
        }
        if(res.status === 404){
            Toast.fail('请求地址错误')
            return false
        }
    }).catch(error => {
        console.log('error',error);
        if(error.timeout){
                Toast.fail('请求超时')
            }else{
                Toast.fail('请求错误')
            }
            return false
     })
}



/*对字符串进行加密*/
export const compileStr =  code => {
    let  c = String.fromCharCode(code.charCodeAt(0) + code.length);
    for(let i = 1; i < code.length; i++ ){
        c += String.fromCharCode(code.charCodeAt(i) + code.charCodeAt(i-1));
    }
    return escape(c);
}

/*字符串进行解密*/
export  const unCompileStr = code => {
    code = unescape(code);
    let c = String.fromCharCode(code.charCodeAt(0) - code.length);
    for(let i = 1; i < code.length; i++){
        c += String.fromCharCode(code.charCodeAt(i) - c.charCodeAt(i-1));
    }
    return c;
}

/*倒计时*/
export   function countDown(allTime, options){
    allTime = allTime - 1000;
    let time = 0;
    options.start && options.start(allTime / 1000);
    const start = () => {
        this.timer = setInterval(() => {
            if(time >= allTime - 1000){
                this.timer && clearInterval(this.timer);
                options.end && options.end();
            }else{
                time += 1000;
                options.change && options.change((allTime - time) / 1000);
            }
        }, 1000);
    };
    start();
    return {
        end:() => {
            if(this.timer){
                clearTimeout(this.timer);
            }
        },
        start: () => start()
    }
}

/*手机号验证*/
export  const checkPhone = str => {
    return /^1[3456789]\d{9}$/.test(str)
}
